﻿using WebApplication1.Infrastructure.DatabaseContext;
using System.Linq.Expressions;
using WebApplication1.Core.Domain.Entities;
using WebApplication1.Core.Domain.RepositoryContracts;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Infrastructure.Repositories {
    public class SheQuRepository : ISheQuRepository {

        private readonly SQLiteDbContext _db;

        public SheQuRepository(SQLiteDbContext dbContext) {
            _db = dbContext;
        }

        public async Task<SheQu> AddSheQu(SheQu sheQu) {
            await _db.SheQu.AddAsync(sheQu);
            await _db.SaveChangesAsync();
            return sheQu;
        }

        public async Task<bool> DeleteSheQu(ushort shequID) {
            _db.SheQu.RemoveRange(_db.SheQu.Where(temp => temp.SheQuID == shequID));
            int rowChanged = await _db.SaveChangesAsync();
            return rowChanged > 0;
        }

        public async Task<IEnumerable<SheQu>> GetAllSheQu() {
            return await _db.SheQu.ToListAsync();
        }

        public async Task<IEnumerable<SheQu>> GetFilteredSheQu(Expression<Func<SheQu, bool>> expression) {
            return await _db.SheQu.Where(expression).ToListAsync();
        }

        public async Task<SheQu?> GetSheQuBySheQuID(ushort shequID) {
            return _db.SheQu.FirstOrDefault(temp => temp.SheQuID == shequID);
        }

        public async Task<bool> UpdateSheQu(SheQu sheQu) {
            SheQu? matched = await _db.SheQu.FirstOrDefaultAsync(temp => temp.SheQuID == sheQu.SheQuID);
            if(matched == null) { return false; }
            matched.MingCheng = sheQu.MingCheng;
            matched.DianHua = sheQu.DianHua;
            matched.ShuJi = sheQu.ShuJi;
            matched.ShuJiDianHua = sheQu.ShuJiDianHua;
            await _db.SaveChangesAsync();
            return true;
        }
    }
}
